package me.pinion.model;

import me.pinion.model.annotation.TableBind;

import java.util.List;

@TableBind(table = "comment")
public class Comment extends XModel<Comment> {
    public static Comment dao = new Comment();
    private User author;
    private List<Comment> nextComments;

    public User getUser() {
        if (author == null) {
            author = User.dao.findById(getLong("author_id"));
        }
        return author;
    }

    public User getAuthor() {
        if (author == null) {
            author = User.dao.findById(getLong("author_id"));
        }
        return author;
    }

    public String getContent() {
        return this.getStr("content");
    }

    public Comment setTarget(XModel<? extends XModel> target){
        this.set("target_id", target.getId());
        this.set("target_type", target.getModelId());
        return this;
    }

    public <T extends XModel<T>> T getTarget(){
        return ModelType.dao.findById(this.getLong("target_type")).getModel(this.getLong("target_id"));
    }

    /**
     *
     * @return if parent is exist
     */
    public boolean hasParentComment(){
        return this.getInt("parent_id") != null;
    }

    /**
     *
     * @return parent
     */
    public Comment getParentComment(){
        return dao.findById(this.getInt("parent_id"))
    }

    public List<Comment> getNextComments(){
        if (this.nextComments == null){
            this.nextComments = Comment.dao.find("SELECT * FROM comment AS co " +
                    "WHERE co.target_type=? " +
                    "AND co.target_id=? " +
                    "AND co.enabled=true ",
                    this.getModelId(),
                    this.getId());
        }
        return this.nextComments;
    }
}
